﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VirtualPress.Tool.Framework;
using System.Web;
using System.Web.SessionState;

namespace VirtualPress.Portal.Biz
{
    public class SecurityBiz
    {
        /// <summary>
        /// security:
        /// login$user:{username} 注：要求必须login，对等验证为username={username}
        /// login$session:{key}={value}
        /// </summary>
        /// <param name="security"></param>
        /// <returns></returns>
        public static bool DownloadFileValid(string security)
        {
            try
            {
                string content = EncodeByBase64.Decode(security);
                if (String.IsNullOrEmpty(content))
                {
                    return false;
                }
                string[] segment = content.Split('$');
                switch (segment[0])
                {
                    case "login":
                        if (!HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
                if (segment.Length == 2)
                {
                    string[] option = segment[1].Split(':');
                    switch (option[0])
                    {
                        case "user":
                            string val = option[1];
                            return val == HttpContext.Current.User.Identity.Name;
                        case "session":
                            string expression = option[1];
                            HttpSessionState session = HttpContext.Current.Session;
                            if (session != null)
                            {
                                try
                                {
                                    object o = session[expression.Split('=')[0]];
                                    if (o.ToString() == expression.Split('=')[1])
                                    {
                                        return true;
                                    }
                                }
                                catch { }
                            }
                            else
                            {
                                LogHelper.Write(CommonLogger.System, LogLevel.Error, "获取HttpContext.Current.Session为null。");
                            }
                            return false;
                        default:
                            return false;
                    }
                }
                return false;
            }
            catch { }
            return false;
        }
    }
}
